package com.cloudree.gllib.shape;

import android.opengl.GLES20;
import android.opengl.Matrix;

import com.cloudree.gllib.BaseApp;
import com.cloudree.gllib.R;
import com.cloudree.gllib.constants.RenderData;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * Created by Administrator on 2017/10/10 0010.
 */
public class DoubleCircle extends Shape {
    FloatBuffer vertexBuffer;
    private float[] vertexData;

    @Override
    public void loadingMaterial() {
        vertexData = RenderData.Cylinder.generateDoubleData(0.5f, 1.0f, 0.25f);
        vertexBuffer = ByteBuffer.allocateDirect(vertexData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer().put(vertexData);
        vertexBuffer.position(0);
    }

    @Override
    public void compileShader() {
        int vertexShader = generateShader(GLES20.GL_VERTEX_SHADER, getVertexShaderCode());
        int fragmentShader = generateShader(GLES20.GL_FRAGMENT_SHADER, getFragmentShaderCode());
        String[] attrs = new String[]{"aPosition"};
        mProgram = generateGlProgram(vertexShader, fragmentShader, attrs);
    }

    @Override
    public void draw(float[] mvpMatrix, float[] modelMatrix, float[] viewMatrix, float[] projectionMatrix) {
        //bind gl handle
        GLES20.glUseProgram(mProgram);
        int matrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        int positionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
        int colorHandle = GLES20.glGetUniformLocation(mProgram, "uColor");

        //set data position
        vertexBuffer.position(0);
        GLES20.glVertexAttribPointer(positionHandle, 4, GLES20.GL_FLOAT, false, 0, vertexBuffer);
        GLES20.glEnableVertexAttribArray(positionHandle);

        Matrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, modelMatrix, 0);
        GLES20.glUniformMatrix4fv(matrixHandle, 1, false, mvpMatrix, 0);

        //draw bottom circle
        GLES20.glUniform4f(colorHandle, 0.6f, 0.6f, 0.6f, 1.0f);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, vertexData.length / 4/2);

        //draw top circle
        GLES20.glUniform4f(colorHandle, 0.9f, 0.9f, 0.9f, 1.0f);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, vertexData.length / 4/2, vertexData.length / 4/2);
    }

    @Override
    public String getVertexShaderCode() {
        return readRawFile(BaseApp.getApp(), R.raw.cylinder_vertex_shader);
    }

    @Override
    public String getFragmentShaderCode() {
        return readRawFile(BaseApp.getApp(), R.raw.cylinder_fragment_shader);
    }
}
